import json
import os

from common import function


def get_default_workflow(json_file=None):
    if not json_file or not os.path.exists(json_file):
        # # 获取当前文件的绝对路径
        # current_path = os.path.abspath(__file__)
        # # 获取当前文件所在的目录
        # current_dir = os.path.dirname(current_path)
        base_dir = os.path.abspath(os.path.join(os.getcwd(), ".."))
        # print(base_dir)
        # json_file = os.path.join(base_dir, r"\workflow\request_prompt.json")
        json_file = r'E:\project\ai_generate\dashboard\workflow\request_prompt.json'
        # print(json_file)
    with open(json_file, "r", encoding="utf-8") as f:
        json_data = json.load(f)
    return json_data


def request_comfyui_prompt(workflow_json=None):
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
    }
    method = "POST"
    url = "http://127.0.0.1:8188/api/prompt"
    data = workflow_json if workflow_json else get_default_workflow()
    json_data = json.dumps(data)
    result = function.call_third_party_api(method, url, headers=headers, params=None, data=json_data, json_data=data)
    # print(result)  # 8f9cdfe3-8544-4c09-91ac-4b388ba81120
    return result


def get_history(prompt_id=None):
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        }
    method = "GET"
    url = f"http://127.0.0.1:8188/api/history"
    # prompt_id: "bde6e3dc-90b9-46f6-992e-fefabd378cac"
    params = {"max_items": 64}
    if prompt_id:
        url = url+"/{}".format(prompt_id)
        params['prompt_id'] = prompt_id
    result = function.call_third_party_api(method, url, headers=headers, params={"max_items": 64})
    # print("get_history\n", result)
    return result


def get_queue():
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
    }
    method = "GET"
    url = "http://127.0.0.1:8188/api/queue"
    result = function.call_third_party_api(method, url, headers=headers)
    return result


if __name__ == '__main__':
    _res = request_comfyui_prompt(workflow_json=None)
    print(_res)
    _prompt_id = "43279ae7-3c1a-4669-8c39-8fd823728d9a"
    _result = get_history(_prompt_id)
    print(_result)
    pass